package com.lz.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.domain.MyUserDetails;
import com.lz.domain.User;
import com.lz.mapper.UserMapper;
import com.lz.service.UserService;
import com.lz.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <pre>
 * @描述：
 * @作者：lizhao
 * @创建时间： 2024/8/19 下午3:09
 * </pre>
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AuthenticationManager authenticationManager;
    /**
     * 验证用户用户信息，并且加密成token返回给前端
     *
     * @param user
     * @return
     */
    @Override
    public String login(User user) {
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        if(authenticate==null){
            throw new RuntimeException("用户名为空");
        }
        MyUserDetails userDetails = (MyUserDetails) authenticate.getPrincipal();
        Integer id = userDetails.getUser().getId();
        String token = JwtUtil.createToken(String.valueOf(id));
        redisTemplate.opsForValue().set("login:"+id, JSON.toJSON(userDetails) );
        return token;
    }
}
